import Util from './util.js'
export default class Cart {
    constructor(id) {
        this.cartStorage = 'CARTLIST' //storage名称
        this.cartRoot = document.querySelector(id) //根据节点
        this.rootEle = this.cartRoot.querySelector('.cart-list') //购物车列表
        this.productAddEle = this.cartRoot.querySelector('.product-add') //添加按钮
        this.addCartEle = this.cartRoot.querySelector('.cart-add') //添加表单弹框
        this.closeEle = this.cartRoot.querySelector('.close') //关闭按钮
    }
    /**
     * 初始化购物车
     *   1. 本地存储storage
     *        查检storage名称是否为空
     *   2. 事件绑定
     *   3. 加载购物车列表
     */
    init(name) {
        //查检storage名称是否为空
        if(!name){
            throw new Error('storage名称不能为空!')
        }
        this.cartStorage = name || this.cartStorage
        let cartStr = localStorage.getItem(this.cartStorage)
        if (!cartStr) {
            let cart = {
                stateAll: false,
                cartList: []
            }
            localStorage.setItem(this.cartStorage, JSON.stringify(cart))
        }
        //加载购物车列表
        this.loadProductList()
        //事件绑定
        this.bindProductAdd()
        this.bindCart()
        this.bindForm()
    }
    /**
     * 动态渲染购物车商品列表数据
     *    商品列表数据到自localStorage
     */
    loadProductList() {
        let cart = this.getStorage()
        //table拼接
        let str = `<table>
                    <tr>
                        <th><input type="checkbox" name="checkall"  ${cart.stateAll?'checked':''}>全选框</th>
                        <th>商品图片</th>
                        <th>商品信息</th>
                        <th>商价</th>
                        <th>数量</th>
                        <th width="100px">总价</th>
                        <th>操作</th>
                    </tr>`
        let trStr = cart.cartList.map(item => {
            return `<tr>
                        <td><input type="checkbox" name="checksingle"  ${item.state?'checked':''} data-index="${item.id}"></td>
                        <td><img src="${item.url}" alt=""></td>
                        <td>${item.name}</td>
                        <td>￥${item.price}</td>
                        <td><input type="button" name="minus" value="-" data-index="${item.id}" ${item.num ==0?'disabled':''}><input type="text" name="amount" value="${item.num}"><input
                                type="button" name="plus" value="+" data-index="${item.id}"></td>
                        <td class="single-price">￥${item.singlePrice}</td>
                        <td> <a href="#">移入收藏</a><br><a href="#" class="del" data-index="${item.id}">删除</a></td>
                    </tr>`
        }).join('')
        str += trStr + '</table>'
        str += `<h2>商品总价:<span class="total-price">￥${Util.totalPrice(cart.cartList)}</span></h2>`
        this.rootEle.innerHTML = str
    }
    /**
     * 添加商品到购物车
     *    持久化存储到localStorage
     */
    bindProductAdd() {
        let _this = this
        const addBtn = this.cartRoot.querySelector('.add-btn')
        const nameInput = this.cartRoot.querySelector('input[name="name"]')
        const priceInput = this.cartRoot.querySelector('input[name="price"]')
        const numInput = this.cartRoot.querySelector('input[name="num"]')
        const urlInput = this.cartRoot.querySelector('input[name="url"]')
        //绑定添加商品事件
        addBtn.addEventListener('click', function (e) {
            //阻止默认行为action
            e = e || window.event
            e.preventDefault()

            let name = nameInput.value
            let price = priceInput.value
            let num = numInput.value
            let url = urlInput.value
            let id = Util.getRandom(1000, 10000)
            //商品对象
            let proudct = {
                id,
                name,
                price,
                num,
                url,
                singlePrice: 0,
                state: false
            }
            //计算价格
            proudct.singlePrice = Number(proudct.price * proudct.num).toFixed(2)

            let cart = _this.getStorage()
            cart.cartList.push(proudct)
            cart.stateAll = false //新增商品全选框设置为false
            _this.saveStorage(cart)

            //清空表单
            nameInput.value = ''
            priceInput.value = ''
            numInput.value = ''
            urlInput.value = ''

            //关闭窗口
            _this.addCartEle.style.display = 'none'
        })
    }
    /**
     * 购物车功能
     */
    bindCart() {
        let _this = this
        this.rootEle.addEventListener('click', function (e) {
            e = e || window.event
            let target = e.target || e.srcElement
            //数量加一
            if (target.value == '+') {
                let id = _this.getProductId(target)
                _this.onCartNum(id, '+')
                return
            }
            //数量加一
            if (target.value == '-') {
                let id = _this.getProductId(target)
                _this.onCartNum(id, '-')
                return
            }
            //删除
            if (target.getAttribute('class') == 'del') {
                let id = _this.getProductId(target)
                _this.deleteProduct(id)
                return
            }
            //全选框
            if (target.getAttribute('name') == 'checkall') {
                _this.onCheckAll()
                return
            }
            //单选框
            if (target.getAttribute('name') == 'checksingle') {
                let id = _this.getProductId(target)
                _this.onCheckSingle(id)
                return
            }
        })
    }
    /**
     * 数量操作
     * @param {*} type 
     */
    onCartNum(id, type) {
        let cart = this.getStorage()
        //2.根据id查找商品
        let product = cart.cartList.find(item => item.id == id)
        type == '+' ? product.num++ : product.num--
        //2.1计算价格
        product.singlePrice = (product.num * product.price).toFixed(2)
        //3.持久存储
        this.saveStorage(cart)
    }
    /**
     * 删除
        1.0 操作节点
            => 根据当前删除节点，查找父节点tr, 执行父节点tr删除操作
        2.0 操作数据 - 商品列表数组
            => 根据当前删除节点，获取删除商品id值，
                根据id查找索引号删除数组商品 
                    let index = productList.findIndex(item=>item.id == id)
                    prouctList.splice(index,1)
     */
    deleteProduct(id) {
        let cart = this.getStorage()
        let index = cart.cartList.findIndex(item => item.id == id)
        cart.cartList.splice(index, 1)
        this.saveStorage(cart)
    }
    /**
     * 全选操作
     */
    onCheckAll() {
        let cart = this.getStorage()
        cart.stateAll = !cart.stateAll
        cart.cartList.forEach(item => item.state = cart.stateAll) //设置所有单选框状态
        this.saveStorage(cart)
    }
    /**
     * 单选操作
     * @param {*} id 
     */
    onCheckSingle(id) {
        let cart = this.getStorage()
        //设置点击单选框状态
        let product = cart.cartList.find(item => item.id == id)
        product.state = !product.state
        //设置全选框状态
        let stateAll = cart.cartList.every(item => item.state == true)
        //持久化存储单选框状态
        cart.stateAll = stateAll
        this.saveStorage(cart)
    }
    /**
     * 绑定表单事件
     */
    bindForm() {
        this.productAddEle.addEventListener('click', () => {
            this.addCartEle.style.display = 'block'
        })
        this.closeEle.addEventListener('click', () => {
            this.addCartEle.style.display = 'none'
        })
    }
    /**
     * 商品ID
     * @returns 
     */
    getProductId(target) {
        let id = target.getAttribute('data-index')
        return id
    }
    /**
     * 保存购物车对象到localStorage并重新渲染页面
     * @param {*} cart
     */
    saveStorage(cart) {
        localStorage.setItem(this.cartStorage, JSON.stringify(cart))
        //重新加载页面
        this.loadProductList()
    }
    /**
     * 获取localStorage购物车
     * @returns 
     */
    getStorage() {
        let cartStr = localStorage.getItem(this.cartStorage)
        let cart = JSON.parse(cartStr) || {}
        return cart
    }
}